import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Typography,
  Card,
  Button,
  Input,
  Menu,
  Space,
  Table,
  Dropdown,
  Tabs,
  message,
  Checkbox,
  Popconfirm,
  Divider,
  Modal,
  Tag,
} from 'antd';
import { connect } from 'umi';
import {
  FieldTimeOutlined,
  PlusOutlined,
  SyncOutlined,
  DownOutlined,
  RightOutlined,
} from '@ant-design/icons';
import moment from 'moment';
import DisbEdit from './components/disbEdit';
import DisbPswEdit from './components/disbPswEdit';

const { TabPane } = Tabs;
const { Search } = Input;
const { Text, Paragraph } = Typography;
const currControl = 'Edu_Distributor';
class ViewPage extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      dataSource: [],
      visible: false,
      selectedRowKeys: [],
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      payload: {},
      record: {},
      keywords: '',
      isApprve: '0',
    };
  }
  componentDidMount() {
    this.fetchDatas();
  }
  fetchDatas = () => {
    this.setState({ loading: true });
    const { pageIndex, pageSize, keywords, isApprve } = this.state;
    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: {
          SkipCount: (pageIndex - 1) * pageSize,
          MaxResultCount: pageSize,
          keywords,
          isApprve,
        },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.result) {
          var dataSource = resp.result.items;
          this.setState({ loading: false, dataSource, totalCount: resp.result?.totalCount });
        }
      });
  };
  onSelectChange = (selectedRowKeys: any) => {
    this.setState({ selectedRowKeys });
  };
  callback = (key: any) => {
    let _this = this;
    this.setState({ isApprve: key }, function () {
      _this.fetchDatas();
    });
  };
  handleAction = (act: string) => {
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length <= 0) {
      message.warning('请至少选择一项！');
      return;
    }
    this.props
      .dispatch({
        type: 'Abp/batchAll',
        payload: { ids: selectedRowKeys, act },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.success) {
          message.info('执行成功！');
          this.fetchDatas();
        }
      });
  };
  handleMenuClick = (e: any) => {
    this.handleAction(e.key);
  };
  onSearch = (value: any) => {
    var keywords = this.state.keywords;
    keywords = value;
    this.setState({ keywords }, () => {
      this.fetchDatas();
    });
  };
  handleAct = (id: any, act: string) => {
    this.props
      .dispatch({
        type: 'Abp/batchAll',
        payload: { ids: [id], act },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.success) {
          message.info('执行成功！');
          this.fetchDatas();
        }
      });
  };
  swithModel = (visible: boolean, record = null) => {
    this.setState({ visible, record });
  };
  swithModel2 = (visible2: boolean, record = null) => {
    this.setState({ visible2, record });
  };
  render() {
    const { loading, dataSource, selectedRowKeys, totalCount, pageSize } = this.state;
    const columns: any = [
      {
        title: '序号',
        width: 60,
        align: 'center',
        key: 'index',
        render: (_: any, __: any, i: any) => {
          return i + 1;
        },
      },
      {
        title: '商户名称',
        dataIndex: 'disbName',
      },
      {
        title: '商户编号',
        dataIndex: 'disbNO',
        render: (text: string) => <Paragraph copyable>{text}</Paragraph>,
      },
      {
        title: '分销商等级',
        dataIndex: 'grade',
      },
      {
        title: '签约时间',
        render: (record: any) => (
          <span>
            <Text type="secondary">
              <FieldTimeOutlined /> {moment(record.startDate).format('YYYY-MM-DD')}~
              {moment(record.endDate).format('YYYY-MM-DD')}
            </Text>
          </span>
        ),
      },
      {
        title: '生效',
        render: (record: any) => (
          <Tag color={record.enabled ? 'green' : 'red'}>{record.enabled ? '已生效' : '未生效'}</Tag>
        ),
      },
      {
        title: '审核状态',
        render: (record: any) => (
          <Checkbox
            checked={record.isApprve}
            onChange={() => this.handleAct(record.id, 'examine')}
          />
        ),
      },
      {
        title: '操作',
        render: (record: any) =>
          dataSource.length >= 1 ? (
            <span>
              <Popconfirm title="确定删除?" onConfirm={() => this.handleAct(record.id, 'delete')}>
                <a>删除</a>
              </Popconfirm>
              <Divider type="vertical" />
              <a onClick={() => this.swithModel(true, record)}>编辑</a>
              <Divider type="vertical" />
              <a onClick={() => this.swithModel2(true, record)}>密码更新</a>
            </span>
          ) : null,
      },
    ];
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        <Menu.Item key="examine" icon={<RightOutlined />}>
          批量审批
        </Menu.Item>
        <Menu.Item key="delete" icon={<RightOutlined />}>
          批量删除
        </Menu.Item>
      </Menu>
    );
    return (
      <PageHeaderWrapper title={false}>
        <Card>
          <Space style={{ marginBottom: 16 }}>
            <Button
              type="primary"
              onClick={() => this.fetchDatas()}
              loading={loading}
              icon={<SyncOutlined />}
            >
              刷新
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => this.swithModel(true)}>
              添加分销商
            </Button>
            <Dropdown overlay={menu}>
              <Button>
                批量操作 <DownOutlined />
              </Button>
            </Dropdown>
            <Search
              style={{ width: 240 }}
              placeholder="输入关键词搜索"
              onSearch={(value) => this.onSearch(value)}
            />
          </Space>
          <Tabs defaultActiveKey="0" type="card" onChange={this.callback}>
            <TabPane tab="全部" key="0"></TabPane>
            <TabPane tab="未审核" key="-1"></TabPane>
            <TabPane tab="已审核" key="1"></TabPane>
          </Tabs>
          <Table
            rowKey="id"
            loading={loading}
            rowSelection={rowSelection}
            columns={columns}
            dataSource={dataSource}
            pagination={{
              onChange: (page) => {
                this.setState({ pageIndex: page }, () => {
                  this.fetchDatas();
                });
              },
              pageSize,
              total: totalCount,
            }}
          />
        </Card>
        <Modal
          title="分销商编辑"
          visible={this.state.visible}
          destroyOnClose={true}
          onCancel={() => this.swithModel(false)}
          footer={false}
          width={700}
        >
          <DisbEdit ParentData={this.state.record} fetchDatas={this.fetchDatas} />
        </Modal>
        <Modal
          title="密码更新"
          visible={this.state.visible2}
          destroyOnClose={true}
          onCancel={() => this.swithModel2(false)}
          footer={false}
        >
          <DisbPswEdit ParentData={this.state.record} />
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
